<template>
  <div class="hero">
    <input
      class="input"
      v-model="keyword"
      type="text"
      placeholder="请输入您要搜索的英雄名"
    />
    <!-- 英雄列表 -->
    <div class="list">
      <div
        class="item"
        :title="item.name"
        @click="goToHeroDetail(item.id)"
        v-for="item in heros"
        :key="item.id"
      >
      <img :src="getImageUrl(item.img)" :alt="item.name" @error="handleImageError" />
        <div class="name">{{ item.name }}</div>
        <div class="mask">
          <img src="../assets/search.png" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>  
import { ElMessage } from "element-plus";
import { reactive, toRefs, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import HeroAPI from "@/api/hero.api"

const router = useRouter();

const goToHeroDetail = (id) => {
  router.push({ path: '/herodetail', query: { id: id } });
};

const state = reactive({
  heros: [],    //英雄列表
  keyword: "",  //搜索关键字
  loading: false
});

// 处理图片URL
const getImageUrl = (imgPath) => {
  if (!imgPath) return '';
  
  // 如果已经是完整的HTTP或HTTPS URL，直接返回
  if (imgPath.startsWith('http://') || imgPath.startsWith('https://')) {
    return imgPath;
  }
  
  // 如果是相对路径，添加API前缀
  if (imgPath.startsWith('/')) {
    return `http://localhost:8080${imgPath}`;
  }
  
  // 如果没有斜杠开头，添加完整路径
  return `http://localhost:8080/${imgPath}`;
}

// 处理图片加载错误
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src);
  // 可以设置默认图片
  event.target.src = '/src/assets/default_hero.png';
}

// 获取全部英雄列表的函数
function findAllHeros() {
  state.loading = true;
  HeroAPI.getHeroList() // 修改：调用获取全部列表的方法
    .then(response => {
      state.heros = response;
    })
    .catch(error => {
      ElMessage.error('获取英雄列表失败: ' + error.message);
      state.heros = []; // 出错时清空列表
    })
    .finally(() => {
      state.loading = false;
    });
}

// 搜索英雄的函数
function searchHeros() {
  if (!state.keyword.trim()) {
    // 如果关键词为空，则显示全部英雄
    findAllHeros();
    return;
  }
  state.loading = true;
  HeroAPI.searchHero(state.keyword) // 修改：调用搜索方法
    .then(response => {
      state.heros = response;
    })
    .catch(error => {
      ElMessage.error('搜索英雄失败: ' + error.message);
      state.heros = [];
    })
    .finally(() => {
      state.loading = false;
    });
}


// 添加防抖搜索
let searchTimer = null;
watch(() => state.keyword, (newVal) => {
  clearTimeout(searchTimer);
  searchTimer = setTimeout(() => {
    searchHeros();
  }, 300);
});

onMounted(() => {
  findAllHeros();
})

// 添加搜索关键词监听
watch(() => state.keyword, (newKeyword) => {
  searchHeros();
});

const { heros,keyword } = toRefs(state);

</script>

<style lang='less'>
.hero {
  position: relative;
  min-height: 100vh;
  margin-left: 20px;
  margin-top: 20px;
  margin-right: 20px;
  
  &::before {
    content: '';
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: url('../assets/heard(2).png');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    background-attachment: fixed;
    opacity: 0.3;
    z-index: -1;
  }
  
  .input {
    height: 40px;
    width: 250px;
    padding: 0 15px;
    border: 2px solid #00a383;
    border-radius: 20px;
    font-size: 16px;
    margin-bottom: 20px;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(5px);
  }

  .list {
    display: grid;
    grid-template-columns: repeat(8, 1fr); /* 每行10个英雄 */
    gap: 8px; /* 间距 */
    .item {
      position: relative;
      cursor: pointer;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 5px;
      img {
        width: 100px;
        height: 100px;
        border-radius: 0;
        border: 2px solid #00a383;
      }
      .name {
        margin-top: 8px;
        color: #333;
        font-size: 20px;
        font-weight: 600;
      }
      &:hover {
        .mask {
          display: block;
        }
        .name {
          color: white;
        }
      }
      .mask {
        display: none;
        position: absolute;
        top: 0;
        left: 0;
        width: 40px;
        height: 40px;
        background: #00a383;
        opacity: 0.8;
        img {
          width: 20px;
          height: 20px;
          margin-top: 50%;
          margin-left: 50%;
          transform: translate(-50%, -50%);
        }
      }
    }
  }
}
</style>